<script setup>
import { reactive, computed, watch, ref } from 'vue'
import { Document } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

import {
	postClassifierAlgorithmChoice, // 分类
	postRegressorAlgorithmChoice, // 回归
} from '@/api/product/machineLearning.js'

const props = defineProps({
	modelValue: {
		type: Object,
		default: () => ({
			formData: {},
		}),
	},
})
const emit = defineEmits(['update:modelValue'])

// 添加loading状态
const isResettingDefault = ref(false)

// 表单规则
const formRules = computed(() => {
	const rules = {}
	if (props.modelValue.algorithmData) {
		props.modelValue.algorithmData.forEach((field) => {
			rules[field.label] = [
				{
					required: true,
					message: `请输入${field.label}`,
					trigger: 'blur',
				},
			]

			// 根据数据类型添加额外验证
			if (field.dataType === '整数') {
				rules[field.label].push({
					type: 'number',
					message: '请输入有效的整数',
					trigger: 'blur',
					transform: (value) => Number(value),
				})
			} else if (field.dataType === '浮点数') {
				rules[field.label].push({
					type: 'number',
					message: '请输入有效的数字',
					trigger: 'blur',
					transform: (value) => Number(value),
				})
			}
		})
	}
	return rules
})

// 表单引用
const formRef = ref(null)

const resetDefault = async () => {
	try {
		isResettingDefault.value = true

		const api =
			props.modelValue.type === '分类'
				? postClassifierAlgorithmChoice
				: postRegressorAlgorithmChoice

		const params = {
			algorithm: props.modelValue.algorithm,
			file_name: props.modelValue.fileName,
			y: props.modelValue.targetFeatureTable
				.filter((item) => item.isTarget === true)
				.map((item) => item.name),
			x: props.modelValue.targetFeatureTable
				.filter((item) => item.isFeature === true)
				.map((item) => item.name),
		}

		console.log('resetDefault params:', params)
		const res = await api(params)
		console.log('resetDefault response:', res)

		// 检查返回结果
		if (res && res.code === 200 && res.data && res.data.best_params) {
			const bestParams = res.data.best_params

			// 清空当前表单数据
			Object.keys(props.modelValue.bestParams).forEach((key) => {
				props.modelValue.bestParams[key] = ''
			})

			// 填充默认值到表单
			Object.keys(bestParams).forEach((paramKey) => {
				// 查找对应的表单字段
				const field = props.modelValue.algorithmData.find(
					(child) => child.label === paramKey || child.enLabel === paramKey
				)

				if (field) {
					let value = bestParams[paramKey]

					// 根据字段类型转换数据类型
					if (field.type === 'number' || field.dataType === '整数') {
						value = parseInt(value)
						if (isNaN(value)) value = bestParams[paramKey] // 如果转换失败，保持原值
					} else if (field.type === 'float' || field.dataType === '浮点数') {
						value = parseFloat(value)
						if (isNaN(value)) value = bestParams[paramKey] // 如果转换失败，保持原值
					}

					props.modelValue.bestParams[field.label] = value
				} else {
					// 如果没有找到完全匹配的字段，尝试直接设置
					if (props.modelValue.bestParams.hasOwnProperty(paramKey)) {
						props.modelValue.bestParams[paramKey] = bestParams[paramKey]
					}
				}
			})

			ElMessage.success('默认参数恢复成功')
		} else {
			ElMessage.error('获取默认参数失败')
		}
	} catch (error) {
		console.error('resetDefault error:', error)
		ElMessage.error('恢复默认参数时发生错误')
	} finally {
		isResettingDefault.value = false
	}
}

const verification = async () => {
	console.log('DynamicForm verification 被调用')
	return new Promise((resolve) => {
		if (formRef.value) {
			console.log('formRef存在，开始验证')
			formRef.value.validate((valid) => {
				console.log('验证完成，结果:', valid)
				resolve(valid)
			})
		} else {
			console.log('formRef不存在')
			resolve(false)
		}
	})
}

// 暴露方法给父组件
defineExpose({
	verification,
})
</script>

<template>
	<div class="component DynamicForm" v-if="props.modelValue.algorithmData">
		<div
			class="component-header"
			style="display: flex; justify-content: space-between; align-items: center"
		>
			<div class="component-header-title">
				{{ props.modelValue.algorithmName }} ({{ props.modelValue.algorithm }})
			</div>

			<el-button
				class="reset-default"
				@click="resetDefault"
				:loading="isResettingDefault"
			>
				贝叶斯自动调参
			</el-button>
		</div>

		<div
			class="DynamicForm-content"
			v-loading="isResettingDefault"
			element-loading-text="贝叶斯自动调参中，请稍后..."
		>
			<el-form
				ref="formRef"
				:model="props.modelValue.bestParams"
				:rules="formRules"
				label-width="150px"
			>
				<el-form-item
					v-for="field in props.modelValue.algorithmData"
					:key="field.label"
					:label="`${field.label}`"
					:prop="field.label"
				>
					<!-- 下拉选择 -->
					<el-select
						v-if="field.type === 'select'"
						v-model="props.modelValue.bestParams[field.label]"
						:placeholder="`请选择${field.label}`"
						style="width: 100%"
						:disabled="isResettingDefault"
					>
						<el-option
							v-for="option in field.options"
							:key="typeof option === 'object' ? option.label : option"
							:label="typeof option === 'object' ? option.label : option"
							:value="typeof option === 'object' ? option.value : option"
						/>
					</el-select>

					<!-- 数字输入 -->
					<el-input-number
						v-else-if="field.type === 'number' || field.type === 'float'"
						v-model="props.modelValue.bestParams[field.label]"
						:placeholder="`请输入${field.label}`"
						style="width: 100%"
						:disabled="isResettingDefault"
						:controls="false"
						class="inputNumber"
					/>

					<!-- 普通输入 -->
					<el-input
						v-else
						v-model="props.modelValue.bestParams[field.label]"
						:placeholder="`请输入${field.label}`"
						:disabled="isResettingDefault"
					/>
				</el-form-item>
			</el-form>
		</div>
	</div>

	<div v-else class="no-data">
		<el-empty description="请先选择算法">
			<template #image>
				<el-icon size="60"><Document /></el-icon>
			</template>
		</el-empty>
	</div>
</template>

<style scoped lang="scss">
@import url('./index.scss');
.DynamicForm {
	&-content {
		padding: 20px;
		width: 1200px;
		margin: 0 auto;
		box-sizing: border-box;
		:deep(.el-form) {
			display: grid;
			grid-template-columns: repeat(3, 1fr);
			gap: 20px;
		}
	}
}

.no-data {
	display: flex;
	justify-content: center;
	align-items: center;
	min-height: 200px;

	.el-empty {
		--el-empty-padding: 20px 0;
	}
}

:deep(.el-form-item__label) {
	font-weight: 500;
	color: var(--el-text-color-regular);
}

:deep(.el-input-number) {
	width: 100%;
}

:deep(.reset-default) {
	border: none;
	padding: 0 !important;
	height: 24px;
	box-sizing: border-box;
	span {
		color: rgba(red, 0.6);
	}
}

:deep(.inputNumber) {
	width: 100% !important;
	.el-input__wrapper {
		padding: 1px 11px !important;
		.el-input__inner {
			text-align: left;
		}
	}
}
</style>
